### adsb_parser/realtime.py

import socket
import threading

class UDPReceiver:
    def __init__(self, queue, ip="0.0.0.0", port=62325, logger=None, raw_logger=None):
        self.queue = queue
        self.ip = ip
        self.port = port
        self.running = False
        self.thread = None
        self.logger = logger or print  # 默认使用 print，如果没有传入
        self.raw_logger = raw_logger  # <--- 加上这句

    def start(self):
        if not self.running:
            self.running = True
            self.thread = threading.Thread(target=self._listen, daemon=True)
            self.thread.start()
            self.logger(f"[UDP监听] 已启动：{self.ip}:{self.port}")

    def stop(self):
        self.running = False
        self.logger("[UDP监听] 停止请求已发送")

    def _listen(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((self.ip, self.port))
        self.logger(f"[UDP监听] 正在监听 UDP {self.ip}:{self.port} ...")

        try:
            while self.running:
                data, _ = sock.recvfrom(16384)
                if self.raw_logger:
                    self.raw_logger(data)
                self.queue.put(data)
        except Exception as e:
            self.logger(f"[UDP监听] 接收异常：{e}")
        finally:
            sock.close()
            self.logger("[UDP监听] 已关闭")
